package com.beizhen.demo.config;

import com.beizhen.demo.entity.StuUser;
import com.beizhen.demo.service.StuUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;
import java.util.Set;

/**
 * 孟希
 * 和数据库交互，看看用户信息，权限信息
 */
public class  MyRealm extends AuthorizingRealm {
    @Autowired
    private StuUserService stuUserService;
    @Autowired
    private HttpSession session;
    //获取权限信息的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("走了查询");
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        //获取用户名
        StuUser stuUser=(StuUser) principals.getPrimaryPrincipal();
        String mail=stuUser.getUMailbox();
        //从数据库查询用户的权限和角色
        Set<String> roles = stuUserService.findRolesByMail(mail);
        if (roles.size()>0 && roles!=null){
            simpleAuthorizationInfo.addRoles(roles);
        }
        Set<String> permissions = stuUserService.findPermissionsByMail(mail);
        if (permissions.size()>0 && permissions!=null){
            simpleAuthorizationInfo.addStringPermissions(permissions);
        }

        return simpleAuthorizationInfo;
    }

    //获取认证信息的方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String mail= (String)token.getPrincipal();
        // token.getCredentials();
        //String mail=((StuUser)token).getUMailbox();
        //获取用户
        StuUser stuUser=stuUserService.findUserByMail(mail);
        if (stuUser==null){
            return null;
        }else {
            session.setAttribute("stuUser",stuUser);
            System.out.println("添加到了session");
            //封装AuthenticationInfo
            ByteSource basalt=new SimpleByteSource(stuUser.getUSalt());
            SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(stuUser,stuUser.getUPwd(),basalt,stuUser.getUMailbox());
            System.out.println("sim"+authenticationInfo);
            return  authenticationInfo;
        }

    }
}
